#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "serial_recv.h"

void* recv_thread(void* arg) {
    char* dev = ((char**)arg)[0];
    int speed = *((int*)((char**)arg)[1]);
    int fd = open_serial(dev, speed);
    if (fd < 0) pthread_exit(NULL);
    printf("Start recv on %s\n", dev);
    recv_loop(fd);
    close(fd);
    pthread_exit(NULL);
}

int main(int argc, char* argv[]) {
    if (argc < 3 || argc % 2 != 1) {
        printf("Usage: %s <dev1> <baud1> [<dev2> <baud2> ...]\n", argv[0]);
        return 1;
    }
    int n = (argc - 1) / 2;
    pthread_t tids[n];
    for (int i = 0; i < n; ++i) {
        char** args = malloc(2 * sizeof(void*));
        args[0] = argv[1 + i * 2];
        int* speed = malloc(sizeof(int));
        *speed = atoi(argv[2 + i * 2]);
        args[1] = (char*)speed;
        pthread_create(&tids[i], NULL, recv_thread, args);
    }
    for (int i = 0; i < n; ++i) pthread_join(tids[i], NULL);
    return 0;
}